package com.xspace.android.xafcommon.util;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class PollingUtils {
	private static HashMap<String, Timer> timerHM = new HashMap<String, Timer>();

	// 开启轮询服务
	public static void startService(final Context context, int seconds, final Class<?> cls, String action) {
		Timer timer = timerHM.get(action);
		if (timer != null) {
			timer.cancel();
		}
		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				context.startService(new Intent(context, cls));
			}
		}, 0, seconds * 1000);

		//		// 获取AlarmManager系统服务
		//		AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		//
		//		// 包装需要执行Service的Intent
		//		Intent intent = new Intent(context, cls);
		//		intent.setAction(action);
		//		PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		//
		//		// 触发服务的起始时间
		//		long triggerAtTime = SystemClock.elapsedRealtime();
		//
		//		// 使用AlarmManger的setRepeating方法设置定期执行的时间间隔（seconds秒）和需要执行的Service
		//		manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime + seconds * 1000, pendingIntent);
	}

	// 开启轮询服务
	public static void startPollingService(Context context, int seconds, Class<?> cls, String action) {
		//		// 获取AlarmManager系统服务
		//		AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		//
		//		// 包装需要执行Service的Intent
		//		Intent intent = new Intent(context, cls);
		//		intent.setAction(action);
		//		PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		//
		//		// 触发服务的起始时间
		//		long triggerAtTime = SystemClock.elapsedRealtime();
		//
		//		// 使用AlarmManger的setRepeating方法设置定期执行的时间间隔（seconds秒）和需要执行的Service
		//		manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, seconds * 1000, pendingIntent);

		Timer timer = timerHM.get(action);
		if (timer != null) {
			timer.cancel();
		}
		timer = null;
	}

	// 停止轮询服务
	public static void stopPollingService(Context context, Class<?> cls, String action) {
		AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, cls);
		intent.setAction(action);
		PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		// 取消正在执行的服务
		manager.cancel(pendingIntent);
	}

}
